﻿//-----------------------------------------------------------------------
// <copyright file="StringX.cs" company="Bugger Sisters Inc.">
//     Copyright (c) Bugger Sisters Inc. All rights reserved.
// </copyright>
// <author>Sergey Tyshkovets</author>
//-----------------------------------------------------------------------

namespace MagicTheGathering.Framework.Extensions
{
    using System;
    using System.Linq;

    using CultureInfo = System.Globalization.CultureInfo;
    using StringBuilder = System.Text.StringBuilder;

    public static class StringX
    {
        public static Boolean EqualsIgnoreCase(this String a, String b)
        {
            return a.Equals(b, StringComparison.OrdinalIgnoreCase);
        }

        public static Boolean ContainsIgnoreCase(this String a, String b)
        {
            return a.ToLower().Contains(b.ToLower(CultureInfo.InvariantCulture));
        }

        public static String[] Split(this String a, String b)
        {
            if (a == null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == null)
            {
                throw new ArgumentNullException("b");
            }

            return a.Split(b.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        public static String Reverse(this String a)
        {
            char[] c = a.ToCharArray();
            Array.Reverse(c);
            return new String(c);
        }

        public static String Merge(this String s1, object s2)
        {
            return String.Format("{0}{1}", s1, s2);
        }

        public static String InverseMerge(this String s1, object s2)
        {
            return String.Format("{0}{1}", s2, s1);
        }

        public static String ReplaceIgnoreCase(this String s, String oldString, String newString)
        {
            int index = 0; 
            int lastIndex = 0;
            var result = new StringBuilder();

            while ((index = s.IndexOf(oldString, index, StringComparison.InvariantCultureIgnoreCase)) != -1)
            {
                result.Append(s, lastIndex, index - lastIndex);
                result.Append(newString);
                lastIndex = index += oldString.Length;
            }

            result.Append(s, lastIndex, s.Length - lastIndex);
            return result.ToString();
        }

        public static Boolean IsNullOrEmpty(this String a)
        {
            return String.IsNullOrEmpty(a);
        }

        public static Boolean IsNullOrWhitespace(this String a)
        {
            return String.IsNullOrEmpty(a) || a.ToCharArray().All(Char.IsWhiteSpace);
        }
    }
}
